package com.gztms.usermgnt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gztms.usermgnt.mapper.MenuMapper;
import com.gztms.usermgnt.mapper.RoleMapper;
import com.gztms.usermgnt.mapper.UserMapper;
import com.gztms.usermgnt.pojo.LoginUser;
import com.gztms.usermgnt.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author Zoey
 * @date 2023/3/8 0:11
 * @Description 实现UserDetailService接口，将从内存查找用户转移到自定义用户
 **/
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String uid) throws UsernameNotFoundException {

        // 根据用户账号查询用户信息
        // TODO 查询LambdaQueryWrapper的用法,这里还有一些问题，比如密码错误啥的
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUid, uid);
        User user = userMapper.selectOne(queryWrapper);
        // 判断用户是否存在
        if (Objects.isNull(user)){
            throw new RuntimeException("用户不存在");
        }


        System.out.println(user);

        //TODO 查询对应的权限信息
//        List<GrantedAuthority> authorities = new ArrayList<>();
        List<String> rolesCodes = (List<String>) roleMapper.selectRoleCode(user.getUid());

        System.out.println("rolesCodes:"+rolesCodes);

//        authorities.add(new SimpleGrantedAuthority();
//        List<String> permissions = new ArrayList<>(Arrays.asList("test","admin"));

        /**
         * List<String> permissions = menuMapper.selectPermsByUserId(user.getUid());
         * */


        // 将数据封装成LoginUser（实现UserDetails接口）,并返回
        return new LoginUser(user,rolesCodes);
    }

}
